#!/bin/bash 

LIB_GPIOD=https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/snapshot/libgpiod-1.6.2.tar.gz
LIB_cJSON=https://github.com/DaveGamble/cJSON/archive/refs/heads/master.zip
LIB_MOSQUITTO=https://mosquitto.org/files/source/mosquitto-2.0.11.tar.gz

function msg_banager()
{
    echo ""
    echo "------------------------------------------------------------------------"
    echo "|   $1"
    echo "+-----------------------------------------------------------------------"
    echo ""
}


function check_result()
{
    if [ $? != 0 ];then
        echo ""
        echo "+-----------------------------------------------------------------------"
        echo "|  $1 "
        echo "+-----------------------------------------------------------------------"
        echo ""
        exit ;
    fi
}

function complie_libgpiod()
{
    PREFIX_PATH=/usr
    SRC_NAME=libgpiod-1.6.2
    PACK_FIX=tar.gz
    IMG_NAME=libgpiod.so

    if [ -f ${PREFIX_PATH}/lib/${IMG_NAME} ] ; then
        msg_banner "$SRC_NAME already compile and installed"
        return 0;
    fi

    msg_banner "Start compile $SRC_NAME "

    if [ ! -f ${SRC_NAME}.${PACK_SUFIX} ] ; then
        #wget https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/snapshot/libgpiod-1.6.2.tar.gz
        wget $LIB_GPIOD
        check_result "ERROR: download ${SRC_NAME} failure"
    fi

    tar -xzf ${SRC_NAME}.${PACK_SUFIX}

    cd ${SRC_NAME}

    ./autogen.sh
    ./configure --enable-tools=yes --prefix=$PREFIX_PATH
    make && sudo make install

    cd -

}

function compile_cJson()
{
    PREFIX_PATH=/usr
    SRC_NAME=master
    PACK_SUFIX=zip
    IMG_NAME=libcjson.so

    if [ -f ${PREFIX_PATH}/lib/${IMG_NAME} ] ; then
        msg_banner "$SRC_NAME already compile and installed"
        return 0;
    fi

    msg_banner "Start compile $SRC_NAME "

    if [ ! -f ${SRC_NAME}.${PACK_SUFIX} ] ; then
        wget $LIB_cJSON
        check_result "ERROR: download ${SRC_NAME} failure"
    fi


    unzip ${SRC_NAME}.${PACK_SUFIX}

    cd cJSON-master
    make && sudo make PREFIX=$PREFIX_PATH install
    cd -
}


function compile_mosquitto()
{
    PREFIX_PATH=/usr
    SRC_NAME=mosquitto-2.0.11
    PACK_SUFIX=tar.gz
    IMG_NAME=libmosquitto.so

    if [ -f ${PREFIX_PATH}/lib/${IMG_NAME} ] ; then
        msg_banner "$SRC_NAME already compile and installed"
        return 0;
    fi
    
    # mosquitto depends on openssl 
    msg_banner "Using apt install openssl library now..."
    sudo apt install -y libssl-dev


    msg_banner "Start compile $SRC_NAME "
    if [ ! -f ${SRC_NAME}.${PACK_SUFIX} ] ; then
        wget $LIB_MOSQUITTO
        check_result "ERROR: download ${SRC_NAME} failure"
    fi


    tar -xzf ${SRC_NAME}.${PACK_SUFIX}

    cd ${SRC_NAME}

    make && sudo make DESTDIR=${PREFIX_PATH} prefix=/ install

    cd -
}

compile_libgpiod

compile_cJson

compile_mosquitto
